package cn.tedu.repository.impl;

import cn.tedu.bo.WorkerAreaBO;
import cn.tedu.dao.WorkerAreaDao;
import cn.tedu.param.WorkerAreaParam;
import cn.tedu.param.WorkerCreateParam;
import cn.tedu.repository.WorkerAreaRepository;
import cn.tedu.repository.cache.impl.RedisCacheEntry;
import cn.tedu.repository.converter.WorkerAreaConverter;
import com.tarena.tp.luban.worker.po.WorkerArea;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;


@Repository
public class WorkerAreaRepositoryImpl extends RedisCacheEntry<WorkerAreaBO> implements WorkerAreaRepository {

    @Autowired
    private WorkerAreaConverter workerAreaConverter;

    @Autowired
    private WorkerAreaDao workerAreaDao;

    @Override
    public void deleteAreas(Long userId) {
        workerAreaDao.delete(userId);
        //设置key值
        String key="luban:worker:area:"+userId;
        //删除缓存
        deleteCache(key);
    }

    @Override
    public void saveAreas(WorkerCreateParam workerCreateParam) {
        //获取要新增的服务区域数据
        List<WorkerAreaParam> workerAreaParams = workerCreateParam.getWorkerAreaParams();
        //完成服务区域数据的类型转换 将其从Param转换成 PO
        ArrayList<WorkerArea> workerAreas = new ArrayList<>();
        for (WorkerAreaParam workerAreaParam : workerAreaParams) {
            //将集合中每一个param对象转换成po，并添加到集合中
            workerAreas.add(workerAreaConverter.param2po(workerAreaParam));
        }
        workerAreaDao.insertAreas(workerAreas);
    }

    @Override
    public List<WorkerAreaBO> findAreas(Long userId) {
        String key="luban:worker:area:"+userId;
        List<WorkerAreaBO> areaBOS;

        if (!exists(key)){
            List<WorkerArea> workerAreas=workerAreaDao.selectWorkerAreasByUserId(userId);
            areaBOS = workerAreaConverter.poList2BoList(workerAreas);
            saveCaches(key,areaBOS);
        }else {
            areaBOS=getCaches(key);
        }

        return areaBOS;
    }
}
